<?php


namespace app\admin\system\controller;


use app\admin\system\logic\MenuLogic;
use app\common\controller\BaseAdminController;
use common\annotation\AuthCode;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class MenuController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new MenuLogic();
    }

    protected $idKey = 'menuId';

    protected $noNeedRight = [
        'listRouter',
        'listMenuIdsByRoleId',
        'listMenuNormal',
        'cascaderList',
    ];

    public function listRouter()
    {
        $uid = request()->uid;

        $data = $this->logic->listRouter($uid);
        return $this->success($data);
    }

    #[AuthCode("system:menu:list")]
    public function list()
    {
        $where = [];
        $this->form['menuName'] && $where[] = ['menuName', 'like', "%{$this->form['menuName']}%"];
        $this->form['auth'] && $where[] = ['auth', 'like', "%{$this->form['auth']}%"];
        $this->form['menuStatus'] && $where[] = ['menuStatus', '=', $this->form['menuStatus']];
        $query = $this->logic->search($where);
        $data = $this->logic->getAll($query);
        return $this->success($data);
    }


    /**
     * 获取正常的菜单
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function listMenuNormal()
    {
        $where = [
            ['menuStatus', '=', 0]
        ];
        $data = $this->logic
            ->where($where)
            ->select()
            ->toArray();
        $menuIds = array_column(array_filter($data, function ($v) {
            return $v['isSpread'] == 0;
        }), 'menuId');
        return $this->success([
            'menuList' => $data,
            'spreadList' => $menuIds,
        ]);
    }

    /**
     * 获取角色已分配的菜单
     * @return Response
     */
    public function listMenuIdsByRoleId()
    {
        // 菜单反选数据[菜单反选只注重子节点，父节点不用返回，子节点都有父节点自然会选中]
        $id = input('id', 0);
        $data = $this->logic->getModel()->alias('a')
            ->join('sys_role_menu b', 'a.menuId=b.menu_id')
            ->where('b.role_id', '=', $id)
            ->order("a.sorted")
            ->field([
                'a.menuId',
                'a.parentId',
            ])
            ->select()
            ->toArray();
        $res = [];
        $hasChild = $this->logic->getModel()
            ->whereIn('parentId', array_column($data, 'menuId'))
            ->column('parentId');
        foreach ($data as $datum) {
            if (!in_array($datum['menuId'], $hasChild)) {
                $res[] = $datum['menuId'];
            }
        }
        return $this->success($res);
    }


    public function cascaderList()
    {
        $where = [
            ['menuType', 'in', [1, 2]],
            ['menuStatus', "=", 0],
        ];
        $data = $this->logic->getList($where, [
            'parentId',
            'menuName as label',
            'menuId as value',
        ]);
        return $this->success($data);
    }

    public function updateSpread()
    {
        $id = input('id');
        $spread = input('spread', 0);
        $data = $this->logic->update(['isSpread' => $spread], [
            'menuId' => $id
        ]);
        return $this->success($data);
    }

    /**
     * 读取信息
     * @return Response
     */
    public function read()
    {
        $model = $this->logic->find(request()->input('id'));
        if ($model) {
            return $this->success($model->toArray());
        } else {
            return $this->error('未查找到信息');
        }
    }

}